#include <sum_gpio.h>
#include <sum_rcu.h>
#include <sum_timer.h>
#include <sum_wfi.h>
#include <sys_mem.h>

#define APB2_FREQ_DEFAULT 8000000
#define TIMER_CLOCK_PSC 65536
#define TIMER_TIMES_MAXN 80
#define TIMER_HIGH_TIMES_MAXN 40

// RCU中将GPIO和TIMER1上电
static void _enable_gpio_timer1(void) {
	rcu_apb1_0_7_s apb1_0_7 = {
		.TIMER1 = 1,
	};
	rcu_apb1_0_7_en_di(apb1_0_7);

	rcu_apb2_0_7_s apb2_0_7 = {
		.GPIOA = 1,
	};
	rcu_apb2_0_7_en_di(apb2_0_7);
}

// 配置GPIO的A1为AF输出
static void _setup_gpio_a1(void) {
	gpio_ctl_0_7_s gpioa_ctl_0_7 = {
		.pin1_ctl = GPIO_OUT_AF_PP_2MHZ,
	};
	gpio_setup_pin_0_7(GPIOA_Q, gpioa_ctl_0_7);
}

__attribute__((noreturn, section(".MAIN"))) void user_main(void) {
	// 未定义全局变量和静态局部变量，因此不需要scatter_load。
	// mem_scatter_load();
	_enable_gpio_timer1();
	_setup_gpio_a1();
	// 配置定时器1，等效于：
	// timer_set_channel_pwm(TIMER1_Q, 1, 65536, 80, 40);
	timer_set_clock_amount_per_count(TIMER1_Q, TIMER_CLOCK_PSC);
	timer_set_times_per_cycle(TIMER1_Q, TIMER_TIMES_MAXN);
	timer_wreg_chcv(TIMER1_Q, TIMER_CHCV_1_R, TIMER_HIGH_TIMES_MAXN);
	timer_chctl_expl_s chctl0 = {
		.channel_13.chctl_out.mode = TIMER_CHCTL_OUT,
		.channel_13.chctl_out.fast_en = 1,
		.channel_13.chctl_out.ctl = TIMER_CHCTL_OUT_LOWER_VALID,
		.channel_13.chctl_out.clear_en = 0,
	};
	timer_channel_setup(TIMER1_Q, TIMER_CHCTL_0_R, chctl0);
	timer_chctl2_expl_s chctl2 = {
		.channel_1_en = 1,
		.channel_1_polarity_neg = 1,
	};
	timer_channel_setup_2(TIMER1_Q, chctl2);
	// 部分配置+开始
	timer_ctl0_expl_s ctl0 = {
		.counter_en = 1,
		.single_pulse_mode = 0,
		.direction = TIMER_CTL0_DIRECTION_UP,
		.counter_align = TIMER_CTL0_COUNTER_ALIGN_EDGE,
		.clock_prescale = TIMER_CTL0_CLOCK_NO_DIV,
	};
	timer_setup_0(TIMER1_Q, ctl0);

	while (1) {
		wfi();
	}
}
